<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/18
 * Time: 15:56
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\cha;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\ChannelCarrier;
use app\common\model\FinancePayment;
use app\common\service\channel\BaseChannel;
use app\common\service\logistics\ChannelService;
use think\facade\Validate;

class CarrierController extends BaseController
{
    /**
     * 承运商列表
     * @date 2020/09/18
     * @author longli
     */
    public function index()
    {
        if(!$this->request->isAjax()) return $this->fetch('index');
        $this->assign('list', ChannelCarrier::order("sort desc,carrier_name")->select());
        return $this->fetch('lists');
    }

    /**
     * 更新承运商
     * @date 2020/09/18
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'carrier_name'  => 'require|unique:channel_carrier,carrier_name',
                'classes' => function($value, $rule)
                {
                    if(empty($value)) return true;
                    if(!BaseChannel::classesExist($value))return "对接类【{$value}】不存在";
                    return true;
                }
            ],[
                'carrier_name.require' => '承运商名称必填',
                'carrier_name.unique' => '承运商已存在',
            ]);
            $data = $this->request->post();
            if(!empty($data['carrier_id']))
            {
                if(($token = $this->validateToken($data)) && !is_array($token)) $this->error($token);
                $data['token'] = $token;
            }
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
            if(!isset($data['status'])) $data['status'] = ChannelCarrier::IS_NO;
        }
        else
        {
            $validate = Validate::make([
                'carrier_id'  => 'require',
            ],[
                'carrier_id.require' => '非法请求',
            ]);
            $data = $this->request->only(['carrier_id', 'status'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        ChannelService::getInstance()->addCarrier($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 录入承运商
     * @date 2020/09/18
     * @author longli
     */
    public function add()
    {
        $this->assign("service", BaseChannel::getAllChannelService());
        $this->assign("pay_type", FinancePayment::$PAY_TYPE);
        $carrierId = $this->request->request("carrier_id");
        if(!empty($carrierId))
        {
            $carrier = ChannelCarrier::get($carrierId);
            $this->assign("carrier", $carrier);
            if(($classes = BaseChannel::getClasses($carrier->classes)) && BaseChannel::classesExist($classes))
            {
                $this->assign("tokenField", $classes::$tokenField);
            }
        }
        return $this->fetch("add");
    }

    /**
     * 删除承运商
     * @date 2020/09/18
     * @author longli
     */
    public function delete()
    {
        $carrierId = $this->request->request("ids");
        if(empty($carrierId)) $this->error('参数错误');
        ChannelCarrier::destroy($carrierId);
        $this->success('删除成功');
    }

    /**
     * 验证承运商录入的 token 信息
     * @param array $post 表单提交过来的数据
     * @return string|array
     * @date 2020/09/17
     * @author longli
     */
    private function validateToken($post = [])
    {
        if(empty($post['classes'])) return [];
        $classes = BaseChannel::getClasses($post['classes']);
        if(!BaseChannel::classesExist($classes)) return "对接类不存在";
        $token = [];
        foreach($post as $k => $v)
        {
            if(Tools::startWith($k, 'token_') && !empty($v) && !is_numeric($v)) $token[substr($k, 6)] = $v;
        }

        $tokenField = $classes::$tokenField;
        $flag = false;
        foreach($tokenField['required'] as $r)
        {
            if(!empty($token[$r['field']]))
            {
                $flag = true;
                break;
            }
        }
        if($flag)
        {
            if(empty($post['api_base_url'])) return "【api请求路径】能不为空";
            if(!Tools::startWith($post['api_base_url'], 'http')) return "【api请求路径】不是正确的url";
            foreach($tokenField['required'] as $r)
            {
                if(empty($token[$r['field']])) return "【{$r['field']}】不能为空";
            }
        }
        return $flag ? $token : [];
    }
}